package com.changgou.service.impl;

import com.changgou.service.WxPayService;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 戴金华
 * @date 2019-12-25 22:23
 */
@Service
public class WxPayServiceImpl implements WxPayService {


    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.partner}")
    private String partner;
    @Value("${weixin.partnerkey}")
    private String partnerkey;
    @Value("${weixin.notifyurl}")
    private String notifyurl;


    @Autowired
    private WXPay wxPay;
    /**
     * 向微信服务器发送请求 将二维码地址返回给controller
     * @param parameterMap
     * @return
     */
    @Override
    public Map nativePay(Map<String, String> parameterMap)  {
        try {
            //参数
            Map<String,String> map = new HashMap();
            //公众账户id
            map.put("appid",appid);
            //商户号
            map.put("mch_id",partner);
            //商品描述
            map.put("body","这个商品很nice");
            //商品订单号
            map.put("out_trade_no",parameterMap.get("orderId"));
            //交易类型
            map.put("trade_type","NATIVE");
            //通知回调地址
            map.put("notify_url",notifyurl);
            //标价金额
            map.put("total_fee","1");

            //获取响应结果
            Map<String, String> resultMap = wxPay.unifiedOrder(map);
            return resultMap;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 查询订单状态
     * @param parameterMap
     * @return
     */
    @Override
    public Map queryOrderPay(Map<String, String> parameterMap) {
        Map<String,String> map = new HashMap();
        //公众账号id
        map.put("appid",appid);
        //商户号
        map.put("mch_id",partner);
        //商户订单号
        map.put("out_trade_no", parameterMap.get("orderId"));
        //随机字符串
        map.put("nonce_str",WXPayUtil.generateNonceStr());

        //调用方法 获取相应结果
        try {
            Map<String, String> resultMap = wxPay.orderQuery(map);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭微信支付订单
     * @param orderId
     * @return
     */
    @Override
    public Map closeOrder(String orderId) {
        Map map = new HashMap();
        map.put("orderId",orderId);
        try {
            Map resultMap = wxPay.closeOrder(map);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
